local M = {}

local newBaloon = function(x, y)
    local baloon = display.newCircle(x, y, 12)
    baloon.isFixedRotation = true
    baloon.type = "baloon"
    baloon.status = "wait"
    baloon.empuje = 80
    baloon.tilt = 0
    baloon:setFillColor(255, 0, 0)
    physics.addBody(baloon, "dinamic", { density = 0.0, friction = 0.0, bounce = 0.0 })

    local function onBaloonCollision(self, event)
        if (event.phase == "began") then
            if (event.other.type ~= nil and event.other.type == "SPIKE") then
                baloon.status = "destroy"
            end
            if (event.other.type ~= nil and event.other.type == "player") then
                baloon.player = event.other
                baloon.status = "hit"
            end

        elseif (event.phase == "ended") then
        end
    end

    baloon.collision = onBaloonCollision
    baloon:addEventListener("collision", baloon)

    --update frame
    local function update(event)
        if (baloon ~= nil) then
            if (baloon.status == "hit") then
                local joint = physics.newJoint("distance", baloon, baloon.player, baloon.x, baloon.y, baloon.player.x, baloon.player.y)
                joint.length = 30 + math.random (0, 10)
                baloon.status = "ready"
            end
            if (baloon.status == "ready") then
                vx, vy = baloon:getLinearVelocity()
                baloon:setLinearVelocity(baloon.tilt * 200, -baloon.empuje)
            end
            if (baloon.status == "destroy") then
                Runtime:removeEventListener("enterFrame", update)
                baloon:removeSelf()
                baloon = nil
            end
        end
    end

    Runtime:addEventListener("enterFrame", update)

    --tilt
    local function onTilt(event)
        if (baloon ~= nil) then
            local tilt = -event.yGravity
            if (tilt > 0.2) then tilt = 0.2 end
            if (tilt < -0.2) then tilt = -0.2 end
            baloon.tilt = tilt
        end
    end

    Runtime:addEventListener("accelerometer", onTilt)

    return baloon
end



M.newBaloon = newBaloon

return M